layui.use(['layer', 'form', 'table', 'configs', 'template'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        config = layui.configs;
    var userRolesId = JSON.parse(sessionStorage.getItem('userInfos')).roleName; // 当前用户角色名
    var allMenu = [];
    getAllMenu();
    //获取表格数据
    getTableData();

    function getTableData() {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getRoles/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(result.data);
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //渲染表格
    function renderTable(data) {
        table.render({
            elem: '.roleTable'
            , id: 'role-table'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarRole'
            , defaultToolbar: ['filter']
            , cols: [[
                {field: 'roleId', title: '角色ID',width: 80}
                , {field: 'roleName', title: '角色名称' ,width: 150}
                , {field: 'roleRemark', title: '角色备注' ,width: 150}
                , {field: 'menuTitle', title: '拥有菜单权限'}
                , {fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(roleTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'addRoles') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增角色",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    form.val("AddForm", {
                        'userRolesId': userRolesId
                    });
                    form.render();
                }
            });
            form.on('submit(AddForm)', function (res) {
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                addRoles(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            $(".addRoles button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    // 监听全选
    form.on('checkbox(checkAll)', function (data) {
        let checked = data.elem.checked; //是否被选中，true或者false
        if (checked) {
            $('.rolesToMeun .menuIdOpt').prop("checked", true);
            $("#checkReverse").prop("checked", false);
        } else {
            $('.rolesToMeun .menuIdOpt').prop("checked", false);
        }
        form.render("checkbox");
    });
    //监听反选
    form.on('checkbox(checkReverse)', function (data) {
        let checked = data.elem.checked;
        if (checked) {
            $("#checkAll").prop("checked", false);
        }
        var item = $(".menuIdOpt");
        item.each(function () {
            if ($(this).prop("checked")) {
                $(this).prop("checked", false);
            } else {
                $(this).prop("checked", true);
            }
        });
        form.render('checkbox');
    });
    //有一个未勾选,则取消全选
    form.on('checkbox(menuIds)', function (data) {
        var item = $(".menuIdOpt");
        for (var i = 0; i < item.length; i++) {
            if (item[i].checked == false) {
                $("#checkAll").prop("checked", false);
                form.render('checkbox');
                break;
            }
        }
        //如果都勾选了，则勾上全选
        var all = item.length;
        for (var i = 0; i < item.length; i++) {
            if (item[i].checked == true) {
                all--;
            }
        }
        if (all == 0) {
            $("#checkAll").prop("checked", true);
            $("#checkReverse").prop("checked", false);
            form.render('checkbox');
        }
    });

    //监听工具条
    table.on('tool(roleTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteUsers(obj, data);
            });
        } else if (layEvent === 'edit') { //编辑角色信息
            var layerIdx = layer.open({
                type: 1,
                title: "编辑角色",
                closeBtn: 1,
                anim: 0,
                offset: '100px',
                area: '500px',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    form.val("rowEditForm", {
                        'userRolesId': userRolesId
                    });
                    form.render();
                }
            });
            form.val("rowEditForm", data);
            form.on('submit(rowEditForm)', function (res) {
                let field = {
                    roleId: res.field.roleId,
                    roleName: res.field.roleName,
                    roleRemark: res.field.roleRemark,
                    userRolesId: res.field.userRolesId
                };
                updateRoleInfo(field);
                layer.close(layerIdx);
                return false;
            });
            $(".editRoles button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }else if (layEvent === 'setRoleMenu'){ // 设置该角色权限
            var layerIdx = layer.open({
                type: 1,
                title: "设置菜单权限",
                closeBtn: 1,
                anim: 0,
                offset: '100px',
                area: '500px',
                content: $('#roleMenu').html(),
                success: function (layero, index) {
                    form.val("rowEditForm", {
                        'userRolesId': userRolesId
                    });
                    form.render();
                    // 查所有菜单，渲染为多选框
                    var ipt = '';
                    allMenu.forEach(item => {
                        if (data.menuTitle.indexOf(item.menuTitle) == -1) {
                            ipt += `<input type="checkbox" lay-skin="primary" name="menuIds[]" value="${item.menuId}" title="${item.menuTitle}" lay-filter="menuIds" class="menuIdOpt">`
                        } else {
                            ipt += `<input type="checkbox" lay-skin="primary" name="menuIds[]" value="${item.menuId}" title="${item.menuTitle}" lay-filter="menuIds" class="menuIdOpt" checked>`
                        }
                    });
                    layero.find('.rolesToMeun').append(ipt);
                    if (data.menuTitle.length == allMenu.length) {
                        $("#checkAll").prop("checked", true);
                    }
                }
            });
            form.val("rowEditForm", data);
            form.on('submit(editRoleMenu)', function (res) {
                // 取所有选中的checkbox
                var valueArr = [];
                $('input.menuIdOpt:checked').each(function () {
                    valueArr.push($(this).val());
                });
                let field = {
                    roleId: res.field.roleId,
                    menuIds: valueArr.join(","),
                    userRolesId: res.field.userRolesId
                };
                updateRoleMenu(field);
                layer.close(layerIdx);
                return false;
            });
            $(".editRoles button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //新增
    function addRoles(dataObj) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/addRoles/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteUsers(obj, data) {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/delete/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete', obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    //更新权限
    function updateRoleMenu(data) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/rolesToMeun/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        });
    }
    // 更新角色信息
    function updateRoleInfo(data) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/updRoles/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        });
    }

    function getAllMenu() {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getMeun/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    allMenu = result.data;
                    form.render();
                } else {
                    layer.msg(result.stateMsg);
                }

            }
        })
    }

    function tableReload() {
        table.reload("role-table", {
            url: config.motorBaseUrl + "/sys/getRoles/v1.0"
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    }

    function refreshTable(type, obj, data) {
        if (type == "update") {
            obj.update(data); //同步更新缓存对应的值
        } else if (type == "delete") {
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }

});
